package com.zn.opit.tech.easyexcel.controller;

import com.alibaba.fastjson.JSON;
import com.zn.opit.tech.easyexcel.domain.R;
import com.zn.opit.tech.easyexcel.domain.excel.BookExcelVO;
import com.zn.opit.tech.easyexcel.exception.EasyExcelException;
import com.zn.opit.tech.easyexcel.exception.EasyExcelExtExceptionTypes;
import com.zn.opit.tech.easyexcel.utils.ExcelUtil;
import com.zn.opit.tech.easyexcel.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequestMapping(value = "/book")
@RestController
public class BookController {

    @GetMapping(value = "/exportBooks", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void test(HttpServletResponse response) {
        List<BookExcelVO> excelVOS = new ArrayList<>();
        excelVOS.add(BookExcelVO.builder().name("西游记").author("吴承恩").publishDate("1592-01-02").build());
        excelVOS.add(BookExcelVO.builder().name("红楼梦").author("曹雪芹").publishDate("1953-03-09").build());
        try {
            ExcelUtil.exportExcel(response, "书籍", "Sheet1", BookExcelVO.class, excelVOS);
        } catch (IOException e) {
            throw new EasyExcelException(EasyExcelExtExceptionTypes.EXPORT_FAILED);
        }
    }

    @PostMapping(value = "importBooks")
    public R importBooks(@RequestParam("file") MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            throw new EasyExcelException(EasyExcelExtExceptionTypes.IMPORT_FILE_IS_EMPTY);
        }
        List<BookExcelVO> bookExcelVOS;
        try {
            bookExcelVOS = ExcelUtil.readExcel(file, BookExcelVO.class);
        } catch (IOException e) {
            throw new EasyExcelException(EasyExcelExtExceptionTypes.IMPORT_PARSE_DATA_FAILED);
        }
        // 字段校验
        ValidationUtil.doValidate(bookExcelVOS);

        for (BookExcelVO bookExcelVO : bookExcelVOS) {
            log.info(JSON.toJSONString(bookExcelVO));
            // 数据拷贝
        }
        // 批量保存
        return R.ok();
    }
}
